using System.Net;

namespace Network 
{
    public class NetManager :Singleton<NetManager> 
    {
        private GameConnection m_tcpConc;
        public GameConnection tcpConc
        {
            get
            {
                return m_tcpConc;
            }
        }

        private MsgDispatcher m_tcpDispt;

        private RUDPConnection udpConc;
        private MsgDispatcher udpDispt;

        public NetManager()
        {
            m_tcpConc = new GameConnection();
            m_tcpDispt = new MsgDispatcher(m_tcpConc);
            udpConc = new RUDPConnection();
            udpDispt = new MsgDispatcher(udpConc);
        }

        public void Connect(string ipAddr, int port)
        {
            m_tcpConc.Connect(ipAddr, port);
        }

        public void UdpConnect(string ipAddr, int port, uint SessionID)
        {
            udpConc.RUDPConnect(new IPEndPoint(IPAddress.Parse(ipAddr), port), SessionID);
        }

        public void Tick(float deltaTime)
        {
            if (m_tcpDispt != null)
                m_tcpDispt.process(deltaTime);
            if (udpDispt != null)
                udpDispt.process(deltaTime);
        }

        public void Close()
        {
            m_tcpConc.Reset(false);
        }

        public void UdpClose()
        {
            udpConc.RUDPReset();
        }

        public void RegistTcpMsg(uint f_id, MsgCallback f_func)
        {
            m_tcpDispt.RegistMsg(f_id, f_func);
        }

        public void UnregistTcpMsg(uint f_id, MsgCallback f_func = null)
        {
            m_tcpDispt.UnregistMsg(f_id, f_func);
        }

        public void RegistUdpMsg(uint f_id, MsgCallback f_func)
        {
            udpDispt.RegistMsg(f_id, f_func);
        }

        public void UnregistUdpMsg(uint f_id, MsgCallback f_func = null)
        {
            udpDispt.UnregistMsg(f_id, f_func);
        }

        public bool IsHost;

        public void SendGameMessage(uint f_id, byte[] content, bool hostOnlyLocal = false)
        {
            if (IsHost)
            {
                udpDispt.DispatchMsg(new MsgObject(f_id, content));
                if (hostOnlyLocal)
                {
                    return;
                }
            }
            udpConc.SendMessage(f_id, content);
        }

        public void SendUdpMessage(uint f_id, byte[] content)
        {
            udpConc.SendMessage(f_id, content);
        }

        public void sendTcpMsg(uint f_id, byte[] content)
        {
            m_tcpConc.SendMessage(f_id, content);
        }
    }
}
